﻿using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace KeZhou.ViewModels
{
    partial class ResetPasswordViewModel : ObservableObject
    {
        private static ResetPasswordViewModel instance;

        public static ResetPasswordViewModel Instance
        {
            get
            {
                return instance ?? (instance = new ResetPasswordViewModel());
            }
        }

        /**
         * 找回密码
         */
        [ObservableProperty]
        private string rpPhone;
        [ObservableProperty]
        private string rpPassword1;
        [ObservableProperty]
        private string rpPassword2;
        [ObservableProperty]
        private string rpCode;

        //重设密码
        //TODO
        public int resetPassword()
        {
            //4 验证码错误
            //6 手机号还未注册
            //9 服务器响应错误，重设失败
            //12 更改密码成功
            string account = RpPhone;
            string password = RpPassword1;
            string code = RpCode;
            int result = resetPasswordCheck(account, password, code);
            return result;
        }

        private int resetPasswordCheck(string phoneNum, string password, string code)
        {
            using (HttpClient client = new HttpClient())
            {
                // 构建请求参数
                var requestData = new Dictionary<string, string>
        {
            { "phoneNum", phoneNum },
            {"mode", "1" },
            {"code", code },
            { "newPassword", password }
        };

                // 构建请求地址
                string requestUrl = "http://www.yym-free.com:4514/kezhou/cloud/resetPassword";

                // 发送POST请求
                HttpResponseMessage response = client.PostAsync(requestUrl, new FormUrlEncodedContent(requestData)).Result;

                // 检查响应是否成功
                if (response.IsSuccessStatusCode)
                {
                    // 解析并返回响应内容，这里假设返回的是整数
                    int result = int.Parse(response.Content.ReadAsStringAsync().Result);
                    return result;
                }
                else
                {
                    // 处理请求失败的情况，可以根据需要进行适当的处理
                    Console.WriteLine("HTTP POST请求失败：" + response.StatusCode);
                    return -1; // 返回一个适当的错误码
                }
            }
        }
    }
}
